package com.smart.framework.proxy;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Method;

/**
 * <p><b>Description:</b>  TODO
 * <p><b>Company:</b>
 *
 * @author created by Jesse Xu at 15:59 on 2019/9/29
 * @version V0.1
 * @classNmae AspectProxy
 */
public class AspectProxy implements Proxy {
    private final static Logger LOGGER = LoggerFactory.getLogger(AspectProxy.class);

    public Object doProxy(ProxyChain proxyChain) throws Throwable {
        Object result = null;
        Class<?> cls = proxyChain.getTargetClass();
        Method method = proxyChain.getTargetMethod();
        Object[] params = proxyChain.getMethodParams();
        
        begin();
        try {
            if(intercept(cls,method,params)){
                before(cls,method,params);
                result = proxyChain.doProxyChain();
                after(cls,method,params);
            }else {
                result = proxyChain.doProxyChain();
            }
           
        } catch (Exception e) {
            LOGGER.error("proxy failure",e);
            error(cls,method,params);
            throw e;
        }finally {
            end();
        }

        return result;
    }

    private void error(Class<?> cls, Method method, Object[] params)throws Throwable {
    }


    private void end() {
    }

    private void after(Class<?> cls, Method method, Object[] params)throws Throwable {
    }

    private void before(Class<?> cls, Method method, Object[] params)throws Throwable  {
    }

    private boolean intercept(Class<?> cls, Method method, Object[] params)throws Throwable  {
        return true;
    }

    private void begin() {
    }
}
